/**
 * Created by asus on 2017/8/29.
 */
//将指标树或者分组树转换成行信息表row_table
/**
 * @param param
 *   {data:a,maxCol:maxColumn,table:$("#myTable")}
 * @param param
 * @returns {{rowNum: number, colNum: number, rowInfo: Array}}
 */
const rowTable = {
  treeToRow: function(param){
    var result = {
      rowNum:0,  //记录指标或分组占用的行数 用于数据表的行数
      colNum:0,  //记录指标或分组占用的列数 用于交叉点表的列数
      rowInfo:[] //记录分组或指标的信息[{rowIndex:,info:},{rowIndex:,info:}] 用于数据表的表格信息标识，行方向的指标或分组信息
    };
    var rowInfo = new Array();
    var colList = new Array();
    var childNodeColArray = new Array();
    var totalSize = 0; //要插入的树的最大宽度
    //参数检查
    if(!param || !param["table"] || !param["data"]){
      alert('参数错误{data:a,colMax:5,table:$("#myTable")}');
      return ;
    }
    //要插入表格的树json
    var data = param["data"];
    //格式化数据添为每个节点加上
    this.formatDataLevel(data);
    //列数 各指标树或分组树的最大深度
    var colMax = 0;
    if(param && param["maxCol"] > 0){
      colMax = param["maxCol"];
    }
    //取得table对象
    var table = param["table"];
    // console.log(table,'table')
    //取得指标树或分组树的宽度
    $.each( data,function(n, value){
      totalSize += visitSubNode(value,0,colList,colMax,"");
    });
    //构造添加的行
    for(var rowIdx =0;rowIdx < totalSize; rowIdx++){
      var str = "<tr>";
      str += getTd(colList,rowIdx);
      str +="</tr>";
      $(str).appendTo(table);
    }
    //取得table td
    function getTd(colList,rowIdx){
      var str = '';
      var columnIdenx = 0;
      for(var i =0;i<colList.length;i++){
        var colArray = colList[i];
        if(colArray != null && colList[i][rowIdx]!= null){
          if(!colList[i][rowIdx].value){
            continue;
          }
          var colspanStr = "";
          if(colList[i][rowIdx].value.level < colMax && colList[i][rowIdx].value.sub.length < 1){
            colspanStr += " colspan = \"" + (colMax - colList[i][rowIdx].value.level +1)+"\"";
          }
          str += "<td style='width: 100px;height: 35px;' rowidx=\""+colList[i][rowIdx].rowIdx+"\"";
          var rowspan = colList[i][rowIdx].size;
          if(rowspan >1){
            str += " rowspan= \""+rowspan + "\"";
          }
          str += colspanStr;
          str += " colidx = \"" + columnIdenx + "\"";
          columnIdenx ++;
          var text = "";
          if(colList[i][rowIdx].value){
            text = colList[i][rowIdx].value.name;
          }
          str += " title = \"" + text + "\"";
          str += "\"><span>"+text+"</span></td>";///*"  prowidx=\""+ colList[i][rowIdx].pRowIdx +*/
          if(colList[i][rowIdx].value && colList[i][rowIdx].value.sub < 1){
            var rinfo = {
              index:rowIdx,
              info:colList[i][rowIdx].value.attribute
            };
            rowInfo.push(rinfo);
          }
        }
      }
      return str;
      //////计算每行第一列！！！！！！！！！！
    }
    //添加节点
    function addNewNode(colList,colIdx,size,value,childCount){
      var colArray = colList[colIdx];
      if(colArray == null){
        colArray = new Array();
        colList[colIdx] = colArray;
      }
      var newData = {
        rowIdx: 0,
        pRowIdx: 0,
        colIdx: colIdx,
        size:size,
        value: value,
        toString:function(){
          return "{rowIdx:"+ this.rowIdx+",pRowIdx:"+ this.pRowIdx+ ",colIdx:"+ this.colIdx+ ",size:"+ this.size +",value:"+ this.value.cat_id + "}";
        }
      };
      var old = colArray.pop();
      if(old != null){
        newData.rowIdx = (old.rowIdx + old.size);
        colArray[old.rowIdx] = old;
      }

      colArray[newData.rowIdx] = newData;

      if(childCount >0){
        var childColList = colList[colIdx +1];
        var tempArray = new Array();
        for(var i=0;i< childCount;i++){
          var temp = childColList.pop();
          if(temp){
            temp.pRowIdx = newData.rowIdx;
            tempArray.push(temp);
          }
        }
        for(var i=0;i< childCount;i++){
          var temp = tempArray.pop();
          if(temp){
            childColList[temp.rowIdx] = temp;
          }
        }
      }
      return newData.rowIdx;
    }
    //获得表的宽度，占用的行数
    function visitSubNode(node,colIndex,colList,colMax,periods){
      
      if(colIndex < colMax -1 && node.sub && node.sub.length >0){
        var _tempPeriod = periods;
        var sub = node.sub;
        var total = 0;
        var childCount = 0;

        //支持报告期下带到所有下级分组节点
        if(node.attribute){
          if(node.attribute.isPeriod && node.attribute.isPeriod === true){
            periods = node.attribute.groupCode;
          }
        }


        //为根节点添加path
        if(node.attribute){
          //报告期层不加到path
            if(node.attribute.path === ""){
              if(node.attribute.ig_type === "iden"){
                node.attribute.path = node.attribute.idenCode;
                node.attribute.pathName = node.attribute.idenName;
              }else if(node.attribute.ig_type === "group"){
                if(node.attribute.isPeriod === false){
                  node.attribute.path = node.attribute.groupCode;
                  node.attribute.pathName = node.attribute.groupName;
                }
              }
            }
        }
        

        $.each( sub, function(n, value){

          //为下级节点添加path
          if(node.attribute){
              if(node.attribute.ig_type === "iden"){
                value.attribute.path = node.attribute.path + "-" + value.attribute.idenCode;
                value.attribute.pathName = node.attribute.pathName + "-" + value.attribute.idenName;
              }else if(node.attribute.ig_type === "group"){
                if(node.attribute.isPeriod === false){
                  value.attribute.path = node.attribute.path + "-" + value.attribute.groupCode;
                  value.attribute.pathName = node.attribute.pathName + "-" + value.attribute.groupName;
                }
              }
          }else{
              if(value.attribute.ig_type === "iden"){
                value.attribute.path = value.attribute.idenCode;
              }else if(value.attribute.ig_type === "group"){
                if(node.attribute.isPeriod === false){
                  value.attribute.path = value.attribute.groupCode;
                }
              }
          }


          var i = visitSubNode(value, colIndex+1,colList,colMax,periods);
          total += i;
          childCount++;
        });
        //支持报告期下带到所有下级分组节点
        if(_tempPeriod && _tempPeriod != ""){
          if(node.attribute){
            if(node.attribute.isPeriod != undefined &&  node.attribute.isPeriod != null&& node.attribute.isPeriod === false){
              node.attribute.period = _tempPeriod;
            }
          }
        }
        addNewNode(colList,colIndex,total,node,childCount)
        return total;
      }else{
        //支持报告期下带到所有下级分组节点
        var _tempPeriod = periods;
        if(node.attribute){
          if(node.attribute.isPeriod && node.attribute.isPeriod === true){
            periods = node.attribute.groupCode;
          }
        }

        //为根节点添加path
        if(node.attribute){
          //报告期层不加到path
            if(node.attribute.path === ""){
              if(node.attribute.ig_type === "iden"){
                node.attribute.path = node.attribute.idenCode;
                node.attribute.pathName = node.attribute.idenName;
              }else if(node.attribute.ig_type === "group"){
                if(node.attribute.isPeriod === false){
                  node.attribute.path = node.attribute.groupCode;
                  node.attribute.pathName = node.attribute.groupName;
                }
              }
            }
        }
        
        var value = null;
        if(!node.isNull){
          value = node;
        }
        if(colIndex < colMax -1){
          node.isNull = true;
          var  count = visitSubNode(node, colIndex+1,colList,colMax,periods);
          //支持报告期下带到所有下级分组节点
          if(_tempPeriod && _tempPeriod != ""){
            if(node.attribute){
              if(node.attribute.isPeriod != undefined &&  node.attribute.isPeriod != null&& node.attribute.isPeriod === false){
                node.attribute.period = _tempPeriod;
              }
            }
          }
          addNewNode(colList,colIndex,1,value,1);
          return count;
        }
        if(_tempPeriod && _tempPeriod != ""){
          if(node.attribute){
            if(node.attribute.isPeriod != undefined &&  node.attribute.isPeriod != null&& node.attribute.isPeriod === false){
              node.attribute.period = _tempPeriod;
            }
          }
        }
        addNewNode(colList,colIndex,1,value,0);
        node.colIndex = colIndex;
        childNodeColArray.push(node);
        return 1;
      }
    }
    //返回建表信息
    result.rowNum = totalSize;
    result.colNum = colMax;
    result.rowInfo = rowInfo;
    return result;
  },
//获得json树的深度
  getDeepth_rowTable: function (data) {
    //计算出各指标树或分组树的最大值
    var maxColumn = 0;
    var ans = 0;
    for(var ddi = 0;ddi < data.length ;ddi ++){
      dfs(data[ddi],1);
      maxColumn = Math.max(ans,maxColumn);
    }
    //递归计算树的深度
    function dfs(data ,deep){
      if ( data.sub.length == 0 )
      {
        ans = Math.max(ans , deep ) ;
        return ;
      }
      else {
        for ( var i = 0;i < data.sub.length;i ++)
          dfs(data.sub[i] , deep + 1) ;
      }
    }
    return maxColumn;
  },
//格式化数据，为各节点添加上等级
  formatDataLevel: function (data) {
    //获得json树的深度
    var temp = 0;
    var getColDeepth = function (data) {
      //计算出各指标树或分组树的最大值
      var maxRow = 0;
      for(var ddi = 0;ddi < data.length ;ddi ++){
        dfs(data[ddi],1);
        maxRow = Math.max(temp,maxRow);
      }
      return maxRow;
    }
    //递归计算树的深度
    var dfs = function(data ,deep){
      if ( data.sub.length == 0 )
      {
        temp = Math.max(temp , deep ) ;
        data.level = deep;
        return ;
      }
      else {
        for ( var i = 0;i < data.sub.length;i ++){
          dfs(data.sub[i] , deep + 1) ;
        }
        data.level = deep;
      }
    }
    getColDeepth(data);
  }
}
export default rowTable
